<template>
    <div>
 <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
        <!-- 头部警告区域 -->
         <el-alert
    title="注意：只允许为第三级分类设置相关参数！"
    type="warning" :closable="false" show-icon></el-alert>
    <!-- 绘制选择商品分类区域 -->
    <el-row class="cat_opt">
        <el-col>
            <span>选择商品分类:</span>
            <!-- 选择商品分类的级联框 -->
    <el-cascader v-model="selectedKeys" :options="cateList"
    :props="{ expandTrigger: 'hover', value: 'cat_id', label: 'cat_name',
     children: 'children'}"
    clearable :class="['cas']" @change="handleChange"></el-cascader>
        </el-col>
    </el-row>
     <el-tabs v-model="activeName" @tab-click="handleTabClick"> <!-- 标签页 -->
    <el-tab-pane label="动态参数" name="many">
        <!-- 添加动态参数 -->
        <el-button type="primary" :disabled="isBtnDisabled" size="mini" @click="addMOveParams">添加参数</el-button>
        <!-- 动态参数表格 -->
         <el-table :data="manyData" border stripe>
             <!-- 展开行 -->
             <el-table-column type="expand">
                 <template slot-scope="scope">
                     <el-tag v-for="(item, i) in scope.row.attr_vals" :key="item.id" closable
                      @close="handleClose(i,scope.row)">
                    {{item}}</el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                    ref="saveTagInput" size="small"
         @keyup.enter.native="handleInputConfirm(scope.row)"
        @blur="handleInputConfirm(scope.row)"></el-input>
        <!-- 添加的按钮 -->
            <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">
                +添加</el-button>
            </template>
             </el-table-column>
          <el-table-column type="index"></el-table-column>
          <el-table-column label="参数名称" prop="attr_name"></el-table-column>
          <el-table-column label="操作">
              <template slot-scope="scope">
                  <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditdialog(scope.row.attr_id)">编辑</el-button>
                  <el-button type="danger" size="mini" icon="el-icon-delete"  @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
          </el-table-column>
      </el-table>
    </el-tab-pane>
    <el-tab-pane label="静态属性" name="only">
        <!-- 添加静态属性 -->
        <el-button type="primary" :disabled="isBtnDisabled" size="mini" @click="addMOveParams">添加属性</el-button>
        <!-- 静态参数表格 -->
          <el-table :data="onlyData" border stripe>
             <el-table-column type="expand">
                 <!-- 静态属性 -->
                  <template slot-scope="scope">
                     <el-tag v-for="(item, i) in scope.row.attr_vals" :key="item.id" closable
                      @close="handleClose(i,scope.row)">
                    {{item}}</el-tag>
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                    ref="saveTagInput" size="small"
         @keyup.enter.native="handleInputConfirm(scope.row)"
        @blur="handleInputConfirm(scope.row)"></el-input>
        <!-- 添加的按钮 -->
            <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">
                +添加</el-button>
            </template>
             </el-table-column>
          <el-table-column type="index"></el-table-column>
          <el-table-column label="属性名称" prop="attr_name"></el-table-column>
          <el-table-column label="操作">
              <template slot-scope="scope">
                  <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditdialog(scope.row.attr_id)">编辑</el-button>
                  <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
              </template>
          </el-table-column>
      </el-table>
    </el-tab-pane>
   </el-tabs>
    </el-card>
    <!-- 添加参数和属性的对话框 -->
    <el-dialog :title="'添加'+titleTested" :visible.sync="addParamsdialogVisible"
  width="50%" @close="addParamsClosed">
<el-form :model="addParamsForm" :rules="addParamsRules" ref="addParamsFormRef" label-width="100px">
  <el-form-item :label="labelTested" prop="attr_name">
    <el-input v-model="addParamsForm.attr_name"></el-input>
  </el-form-item>
</el-form>
 <span slot="footer" class="dialog-footer">
    <el-button @click="addParamsdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addParamsTrue">确 定</el-button>
  </span>
</el-dialog>
<!-- 编辑参数和属性的对话框 -->
 <el-dialog :title="'编辑'+titleTested" :visible.sync="editParamsdialogVisible"
  width="50%" @close="editParamsClosed">
<el-form :model="editParamsForm" :rules="addParamsRules" ref="editParamsFormRef" label-width="100px">
  <el-form-item :label="labelTested" prop="attr_name">
    <el-input v-model="editParamsForm.attr_name"></el-input>
  </el-form-item>
</el-form>
 <span slot="footer" class="dialog-footer">
    <el-button @click="editParamsdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editParamsTrue">确 定</el-button>
  </span>
</el-dialog>
    </div>
</template>

<script>
export default {
  data () {
    return {
      selectedKeys: [], // 级联狂选中的数据
      cateList: [], // 级联选择器中的数据
      activeName: 'many', // 被激活的页签名称
      manyData: [], // 动态参数数据
      onlyData: [], // 静态参数数据
      addParamsForm: {
        attr_name: ''
      }, // 添加动态参数的数据
      addParamsdialogVisible: false, // 控制添加动态参数对话框的打开与关闭
      addParamsRules: {
        // 验证规则
        attr_name: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ]
      },
      editParamsdialogVisible: false, // 编辑对话框的打开与关闭
      editParamsForm: {}
    }
  },
  methods: {
    async getCateList () { // 获取分类的数据列表
      const { data: res } = await this.$http.get('categories');
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类列表数据失败');
      }
      // console.log(res.data);
      this.cateList = res.data;
    },
    handleChange () {
      this.getParamsData();
      if (this.selectedKeys.length !== 3) {
        this.manyData = [];
        this.onlyData = [];
      }
    },
    handleTabClick () {
      // tab标签点击事件的函数
      // console.log(this.activeName);
      this.getParamsData();
    },
    async getParamsData () { // 获取相关参数列表数据
      // 囧脸选中项变化触发
      if (this.selectedKeys.length !== 3) { // 证明选中的不是三级分分类
        this.selectCateKeys = [];
        return false;
      }
      // 根据所处的ID和所处的面板选择对应的参数,get方法使用params传递参数
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } });
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败');
      }
      // console.log(res.data);
      res.data.forEach(element => {
        element.attr_vals = element.attr_vals
          ? element.attr_vals.split(' ') : [] // 字符串转化为数组
        element.inputVisible = false;
        element.inputValue = '';
      })
      // console.log(res.data)
      if (this.activeName === 'many') { // 动态参数的数据 {
        this.manyData = res.data;
      } else {
        this.onlyData = res.data;
      }
    },
    addMOveParams () {
      // 添加动态参数
      this.addParamsdialogVisible = true;
    },
    addParamsClosed () {
      this.$refs.addParamsFormRef.resetFields();
    },
    addParamsTrue () {
      // 添加参数、属性（确定按钮）
      this.$refs.addParamsFormRef.validate(async valid => {
        if (!valid) {
          return false;
        }
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addParamsForm.attr_name,
          attr_sel: this.activeName
        });
        if (res.meta.status !== 201) {
          return this.$message.error('添加失败');
        }
        this.$message.success('添加成功');
        this.getParamsData();
        this.addParamsdialogVisible = false;
      })
    },
    // 点击按钮打开修改的对话框
    async showEditdialog (attrId) {
      // console.log(tt)
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${attrId}`,
        { params: { attr_sel: this.activeName } });
      if (res.meta.status !== 200) {
        // console.log(res.data);
        return this.$message.error('查询参数信息失败');
      }
      this.editParamsForm = res.data;
      // console.log(res.data);
      // this.getParamsData();
      this.editParamsdialogVisible = true;
    },
    editParamsClosed () {
      this.$refs.editParamsFormRef.resetFields();
    },
    editParamsTrue () {
      this.$refs.editParamsFormRef.validate(async valid => {
        if (!valid) return false;
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`,
          {
            attr_name: this.editParamsForm.attr_name,
            attr_sel: this.activeName
          });
        if (res.meta.status !== 200) {
          return this.$message.error('修改失败');
        }
        this.$message.success('修改成功');
        this.getParamsData();
        this.editParamsdialogVisible = false;
      })
    },
    async removeParams (attrId) {
      const confirmResult = await this.$confirm('此操作将永久删除该参数/属性, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除!');
      }
      // console.log(data);
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${attrId}`);
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('删除参数失败!');
      }
      this.getParamsData();
      this.$message.success('删除参数成功!');
    },
    async handleInputConfirm (data) {
      // 文本框失去焦点或者按下了enter建
      // console.log('ok');
      if (data.inputValue.trim().length === 0) {
        data.inputValue = '';
        data.inputVisible = false;
        return false;
      }
      // 用户输入内容以后的后续处理
      data.attr_vals.push(data.inputValue.trim());
      data.inputValue = '';
      data.inputVisible = false;
      this.saveAttr(data);
    },
    showInput (data) {
      data.inputVisible = true;
      // $nextTic的作用是当页面被重新渲染以后才执行回调函数中的代码
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus(); // 文本框自动获得焦点
      });
    },
    async saveAttr (data) {
      // 发起网络请求保存数据
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${data.attr_id}`, {
        attr_name: data.attr_name,
        attr_sel: data.attr_sel,
        attr_vals: data.attr_vals.join(' ')
      });
      if (res.meta.status !== 200) {
        return this.$message.error('添加失败');
      }
      this.$message.success('修改成功');
    },
    handleClose (i, data) {
      data.attr_vals.splice(i, 1);
      this.saveAttr(data);
    }
  },
  created () {
    this.getCateList();
  },
  computed: {
    // 计算属性
    isBtnDisabled: function () { // 按钮的禁用与启用
      if (this.selectedKeys.length !== 3) {
        return true;
      }
      return false;
    },
    // 当前选中的三级分类的ID
    cateId () {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[2];
      }
      return null;
    },
    titleTested () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    },
    labelTested () {
      if (this.activeName === 'many') {
        return '新参数名称:'
      } else {
        return '新属性名称:'
      }
    }
  }

}
</script>
<style lang="less" scoped>
.cat_opt{
    margin: 15px 0;
}
.cas{
    margin-left: 10px;
}
.el-tag{
    margin: 0 10px;
}
.input-new-tag{
    width: 120px;
}
</style>
